package data;

import java.util.ArrayList;
import java.util.Date;

import models.MessageQueue;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class MessageQueueData {
	private Objectify ofy;
	
	private int limit = 20;
	
	private int page = 1;
	
	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public MessageQueueData() {
		try {
			ObjectifyService.register(MessageQueue.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public void insert(MessageQueue messageQueue) {
		ofy.put(messageQueue);
	}
	
	public MessageQueue getMessageQueueForCrawler() {
		MessageQueue messageQueue = new MessageQueue();
		messageQueue = ofy.query(MessageQueue.class).filter("isDone", false).get();
		return messageQueue;
	}
	
	public MessageQueue getById(String id) {
		MessageQueue messageQueue  = new MessageQueue();
		try {
			messageQueue = ofy.get(new Key<MessageQueue>(MessageQueue.class, id));
		} catch (Exception e) {
			messageQueue = null;
		}
		return messageQueue;
	}
	
	public ArrayList<MessageQueue> getAll() {
		ArrayList<MessageQueue> mqs = new ArrayList<MessageQueue>();
		
		int start = (page - 1) * limit;
		Query<MessageQueue> q = ofy.query(MessageQueue.class).limit(limit).offset(start);
		
		for (MessageQueue messageQueue: q) {
			mqs.add(messageQueue);
		}
		
		return mqs;
	}
	
	public ArrayList<MessageQueue> getByAutoSiteId(String autoSiteId) {
		ArrayList<MessageQueue> mqs = new ArrayList<MessageQueue>();
		
		int start = (page - 1) * limit;
		Query<MessageQueue> q = ofy.query(MessageQueue.class).filter("autoSiteId", autoSiteId).limit(limit).offset(start);
		
		for (MessageQueue messageQueue: q) {
			mqs.add(messageQueue);
		}
		
		return mqs;
	}
	
	public void deleteAll() {
		Query<MessageQueue> q = ofy.query(MessageQueue.class).limit(500);
		for (MessageQueue messageQueue: q) {
			ofy.delete(messageQueue);
		}
	}
}
